import { asyncRoutes, constantRoutes } from "@/router";
// import _import from "@/router/modules/_import_production";
// import Layout from "@/layout";
// import { MessageBox, Message } from "element-ui";
// import { delete } from "vue/types/umd";
// function _imp(name) {
//   return function () {
//     return import(`@/views${name}`);
//   };
// }
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

const state = {
  routes: [],
  addRoutes: []
};
// const loadView = view => {
//   return resolve => require([`@/views${view}`], resolve);
// };
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = routes;
  }
};
const actions = {
  // 动态获取路由 过滤出当前用户拥有的路由
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      // apis.getPermissionInfo().then(function(res) {

      const arr = constantRoutes.concat(asyncRoutes)
      commit("SET_ROUTES", arr);
      resolve(arr);
      // });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
